package com.whfc.ms.api.hdc.service.impl;

import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.hdc.dto.AppDeviceUpgradeDTO;
import com.whfc.hdc.dto.AppDeviceUpgradePackageDTO;
import com.whfc.hdc.service.AppDeviceOtaService;
import com.whfc.ms.api.hdc.service.MsUpgradeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.MessageFormat;
import java.util.List;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-12-25 15:24
 */
@Service
public class MsUpgradeServiceImpl implements MsUpgradeService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String masterOssKeyPattern = "{0}/master_upgrade_{1}_{2}.bin";

    private String slaveOssKeyPattern = "{0}/slave_upgrade_{1}_{2}.bin";

    private String masterUpgradeFile = "master_upgrade_{0}_{1}.bin";

    private String slaveUpgradeFile = "slave_upgrade_{0}_{1}.bin";

    @DubboReference(interfaceClass = AppDeviceOtaService.class, version = "1.0.0")
    private AppDeviceOtaService upgradeService;

    @Value("${iot.upgrade.oss.dir}")
    private String updateFileOssKey;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public PageData<AppDeviceUpgradePackageDTO> upgradePackageList(Integer deviceType, Integer pageNum, Integer pageSize) throws BizException {
        return upgradeService.upgradePackageList(deviceType, pageNum, pageSize);
    }

    @Override
    public void addUpgradePackage(Integer deviceType, String masterVer, String slaveVer, MultipartFile file) {

        //验证参数
        if (StringUtils.isBlank(masterVer) && StringUtils.isBlank(slaveVer)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "版本号不能为空");
        }

        //验证升级包名
        String fileName = null;
        if (StringUtils.isNotBlank(masterVer)) {
            fileName = MessageFormat.format(masterUpgradeFile, deviceType, masterVer);
        } else if (StringUtils.isNotBlank(slaveVer)) {
            fileName = MessageFormat.format(slaveUpgradeFile, deviceType, slaveVer);
        }
        String fileOriginalFilename = file.getOriginalFilename();
        if (!fileOriginalFilename.endsWith(fileName)) {
            logger.info("fileOriginalFilename:{},fileName:{}", fileOriginalFilename, fileName);
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "升级包文件名不符合要求");
        }

        //上传文件
        String ossKey = null;
        if (StringUtils.isNotBlank(masterVer)) {
            ossKey = MessageFormat.format(masterOssKeyPattern, updateFileOssKey, deviceType, masterVer);

        } else if (StringUtils.isNotBlank(slaveVer)) {
            ossKey = MessageFormat.format(slaveOssKeyPattern, updateFileOssKey, deviceType, slaveVer);
        }
        try {
            fileHandler.upload(ossKey, file.getInputStream());
        } catch (Exception ex) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "上传文件失败");
        }

        //保存升级包
        AppDeviceUpgradePackageDTO dto = new AppDeviceUpgradePackageDTO();
        dto.setDeviceType(deviceType);
        dto.setMasterVer(masterVer);
        dto.setSlaveVer(slaveVer);
        dto.setFileName(fileName);
        upgradeService.addUpgradePackage(dto);
    }

    @Override
    public void delUpgradePackage(Integer packageId) throws BizException {
        upgradeService.delUpgradePackage(packageId);
    }

    @Override
    public PageData<AppDeviceUpgradeDTO> upgradeDeviceList(Integer pageNum, Integer pageSize, Integer packageId, Integer state, String keyword) throws BizException {
        return upgradeService.upgradeDeviceList(pageNum, pageSize, packageId, state, keyword);
    }

    @Override
    public ListData<AppDeviceUpgradeDTO> upgradeDeviceList(Integer packageId) throws BizException {
        List<AppDeviceUpgradeDTO> list = upgradeService.upgradeDeviceList(packageId);
        return new ListData<>(list);
    }

    @Override
    public void addUpgradeDevice(Integer packageId, List<Integer> deviceIdList) throws BizException {
        upgradeService.addUpgradeDevice(packageId, deviceIdList);
    }

    @Override
    public void delUpgradeDevice(Integer upgradeId) throws BizException {
        upgradeService.delUpgradeDevice(upgradeId);
    }
}
